from typing import Tuple, Union

import ujson
from fastapi.encoders import jsonable_encoder
from peewee import DoesNotExist

from cache.pay_way_cache import PayWayCache
from common.g.g import G_LOGGER
from common.model.payment.pay import TotalPayWay, TenantAliPayConfig
from common.utils.resp import ERROR, RC
from common.v.v import PAYWAY, DATAORCODE
from service.base import Service


class PayWayService(Service):

    CACHE_CLS = PayWayCache

    async def get_pay_way_list(self) -> Tuple[bool, DATAORCODE]:
        try:
            cache_data = await self.cache.get_pay_way_list(PAYWAY.TOTAL_PAY_WAY_INFO)
            if cache_data:
                return True, DATAORCODE(data=ujson.loads(cache_data))
        except Exception as e:
            G_LOGGER.exception(f"获取缓存数据失败:{e}")
        try:
            res = await TotalPayWay.search_instances(self.mgw)
        except Exception as e:
            G_LOGGER.exception(f"获取数据失败:{e}")
            return False, DATAORCODE(data=None, code=RC.DB_ERROR, msg="服务异常")

        data = list(res)
        try:
            if data:
                await self.cache.set_total_pay_way_info_list(PAYWAY.TOTAL_PAY_WAY_INFO, ujson.dumps(jsonable_encoder(data)), ex=30 * 60)
            else:
                await self.cache.set_total_pay_way_info_list(PAYWAY.TOTAL_PAY_WAY_INFO, ujson.dumps([]), ex=60)
        except Exception as e:
            G_LOGGER.exception(f"更新缓存数据失败:{e}")
        return True, DATAORCODE(data=data)


class TenantPayConfigService(Service):

    async def get_tenant_ali_pay_config(self, tenant_id):
        try:
            res = await TenantAliPayConfig.get_instance(self.mgw,
                                                        condition={"tenant_id": tenant_id},
                                                        fields=["appid", "app_private_key", "ali_public_key", "domain",
                                                                "encrypt_type", "encrypt_key", "return_url",
                                                                "notify_url",
                                                                "sign_type", "charset"]
                                                        )
        except DoesNotExist:
            G_LOGGER.error(f"租户:{tenant_id}缺失支付配置,请补充！")
            return False, DATAORCODE(data=None, code=RC.NOT_EXIST, msg="缺失配置,请补充")
        except Exception as e:
            G_LOGGER.exception(e)
            return False, DATAORCODE(data=None, code=RC.DB_ERROR, msg="服务异常")
        return True, DATAORCODE(data=res)

    async def get_ali_pay_config_by_appid(self, appid):
        try:
            res = await TenantAliPayConfig.get_instance(self.mgw,
                                                        condition={"appid": appid},
                                                        fields=["appid", "app_private_key", "ali_public_key", "domain",
                                                                "encrypt_type", "encrypt_key", "return_url", "notify_url",
                                                                "sign_type", "charset"])
        except DoesNotExist:
            G_LOGGER.error(f"租户:{appid}缺失get_ali_pay_config_by_appid支付配置,请补充！")
            return False, DATAORCODE(data=None, code=RC.NOT_EXIST, msg="缺失配置,请补充")
        except Exception as e:
            G_LOGGER.exception(e)
            return False, DATAORCODE(data=None, code=RC.DB_ERROR, msg="服务异常")
        return True, DATAORCODE(data=dict(res))

    async def add_ali_pay_config(self):
        ...